package com.knowledge.plus.创建线程and线程池.线程间隔离;

import lombok.SneakyThrows;

import java.text.SimpleDateFormat;
import java.util.Random;

/**
 * 普通方式声明变量
 *
 * @author TPF
 * @since 2024/1/24
 */
public class ThreadDemo implements Runnable {

    // SimpleDateFormat 不是线程安全的
    private SimpleDateFormat TL_FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    public static void main(String[] args) throws InterruptedException {
        ThreadDemo obj = new ThreadDemo();
        for (int i = 0; i < 10; i++) {
            Thread t = new Thread(obj, "" + i);
            Thread.sleep(new Random().nextInt(1000));
            t.start();
        }
    }

    @SneakyThrows
    @Override
    public void run() {
        System.out.println("Thread Name= " + Thread.currentThread().getName() + " 修改前 formatter = " + TL_FORMATTER.toPattern());

        // formatter pattern is changed here by thread, but it won't reflect to other threads
        TL_FORMATTER = new SimpleDateFormat("yyyy-MM-dd");

        System.out.println("Thread Name= " + Thread.currentThread().getName() + " 修改后 formatter = " + TL_FORMATTER.toPattern());
    }

}
